import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mac
 * Date: 2022-10-27
 * Time: 19:14
 */
public class HashBuck {

    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;

    public static final double DEFAULT_LOADFACTOR = 0.75;

    public HashBuck() {
        this.array = new Node[10];
    }

    /**
     * put函数
     * @param key
     * @param val
     */
    public void put(int key,int val){
        //1.找到key所在位置
        int index = key % this.array.length;

        //2.遍历这个下标的链表，看是不是有相同的key，有的话要更新val值的
        Node cur = array[index];
        while (cur != null){
            if (cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //3.没有key这个元素, 头插法
        Node node = new Node(key, val);
        node.next = array[index];
        array[index] = node;
        this.usedSize++;
        //4.插入元素成功后，检查当前哈希表的负载因子
        if (loadFactor() > DEFAULT_LOADFACTOR){
            resize();//重新hash
        }
    }

    //如果扩容数组 那么数组里面的每个链表每个元素都要重新hash！！！
    private void resize() {
        Node[] newArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null){
                int index = cur.key % newArray.length;//获取新的下标
                //就是把cur这个节点，以头插方式插入到新的数组
                Node curNext = cur.next;
                cur.next = newArray[index];//先绑定到后面
                newArray[index] = cur;//绑定前面
                cur = curNext;
            }
        }
        array = newArray;
    }

    private double loadFactor() {
        return  1.0 * usedSize / array.length;
    }
    /**
     * get函数
     * @param key
     * @return
     */
    public int get(int key) {
        int index = key % this.array.length;
        Node cur = array[index];
        while (cur != null){
            if (cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

    public static void main(String[] args) {
        HashBuck hashBuck = new HashBuck();
        hashBuck.put(1,1);
        hashBuck.put(12,12);
        hashBuck.put(3,3);
        hashBuck.put(6,6);
        hashBuck.put(7,7);
        hashBuck.put(2,2);
        hashBuck.put(11,11);
        hashBuck.put(8,8);
        System.out.println(hashBuck.get(11));
    }
}
